package com.scraper.articles.web.controller;

import com.scraper.articles.web.model.chart.ChartDataItem;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.net.URL;
import java.text.ParseException;
import java.util.*;

@Controller
@RequestMapping("/chart")
public class ChartController {

    @RequestMapping(value = {"/"})
    public String chart() throws IOException, ParseException {
        return "app/chartView";
    }

    @RequestMapping(value = {"/data/{searchTerm}"})
    public
    @ResponseBody
    List<ChartDataItem> chartData(@PathVariable String searchTerm) throws IOException, ParseException {
        List<ChartDataItem> chartDataItems = new ArrayList<>();
        URL resource = getClass().getResource("/data/stock/" + searchTerm.toLowerCase() + ".csv");
        Reader in = new FileReader(resource.getFile());
        Iterable<CSVRecord> records = CSVFormat.EXCEL.withHeader("Date", "Open", "High", "Low", "Close", "Volume", "Adj	Close").parse(in);
        int i = 0;
        for (CSVRecord record : records) {
            String date = record.get("Date");
            String volume = record.get("Volume");
            if (i != 0) {
                Date parseDate = DateUtils.parseDate(date, Locale.UK, "yyyy-mm-d");
                chartDataItems.add(new ChartDataItem(date, Long.valueOf(volume)));
            }
            i++;
        }
        Collections.reverse(chartDataItems);
        return chartDataItems;
    }
}
